package com.cy.module;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.cy.BasicController;
import com.cy.ext.plugin.CLMPRestful;
import com.cy.ext.plugin.route.ControllerBind;
import com.jfinal.aop.Before;
import com.jfinal.kit.JsonKit;
import com.jfinal.plugin.activerecord.Page;

import java.util.List;

@ControllerBind(parentKey = "/res/_webApi")
@Before(value = {CLMPRestful.class})
public abstract class WebApiController extends BasicController {
    protected final int DEFAULT_PAGE = 1;
    protected final int DEFAULT_PAGE_SIZE = 20;

    public abstract void index();

    public void show(){}

    public void update(){}

    public void save(){}

    public void delete(){}

    /**
     * 获取当前页码.
     *
     * @return
     */
    protected int getPageIndex() {
        Integer pageIndex = getParaToInt("p");
        if (pageIndex == null || pageIndex < 1) {
            pageIndex = DEFAULT_PAGE;
        }
        return pageIndex;
    }

    /**
     * 默认读取列表为JSON
     *
     * @param page
     */
    protected void renderPage(Page page,Integer code) {
        JSONObject renderObj = new JSONObject();
        JSONObject dataObj = new JSONObject();
        List dataList = page.getList();
        JSONArray result = JSON.parseArray(JsonKit.listToJson(dataList, 5));
        renderObj.put("code",code);

        dataObj.put("list", result);
        dataObj.put("total", page.getTotalRow());
        dataObj.put("totalPage", page.getTotalPage());
        dataObj.put("pageSize", page.getPageSize());
        dataObj.put("pageIndex", page.getPageNumber());
        renderObj.put("data",dataObj);

        renderJson(renderObj);
    }
    /**
     * 默认读取列表为JSON
     *
     * @param page
     */
    protected void renderBuiPage(Page page,Integer code) {
        JSONObject dataObj = new JSONObject();
        List dataList = page.getList();
        JSONArray result = JSON.parseArray(JsonKit.listToJson(dataList, 5));
        dataObj.put("rows", result);
        dataObj.put("total", page.getTotalRow());
        dataObj.put("totalPage", page.getTotalPage());
        dataObj.put("pageSize", page.getPageSize());
        dataObj.put("pageIndex", page.getPageNumber());

        renderJson(dataObj);
    }

}
